/*
 * Copyright 2019-present Open Networking Foundation
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.onosproject.p4runtime.ctl.codec;

import org.onosproject.net.pi.model.PiPacketOperationType;
import org.onosproject.net.pi.model.PiPipeconf;
import org.onosproject.net.pi.runtime.PiPacketOperation;
import org.onosproject.p4runtime.ctl.utils.P4InfoBrowser;
import p4.config.v1.P4InfoOuterClass;
import p4.v1.P4RuntimeOuterClass;

import static org.onlab.util.ImmutableByteSequence.copyFrom;
import static org.onosproject.p4runtime.ctl.codec.Codecs.CODECS;

/**
 * Codec for P4Runtime PacketIn. Only decoding is supported, as encoding is not
 * meaningful in this case (packet-ins are always generated by the server).
 */
public final class PacketInCodec
        extends AbstractCodec<PiPacketOperation,
        P4RuntimeOuterClass.PacketIn, Object> {

    private static final String PACKET_IN = "packet_in";

    @Override
    protected P4RuntimeOuterClass.PacketIn encode(
            PiPacketOperation piEntity, Object ignored, PiPipeconf pipeconf,
            P4InfoBrowser browser)
            throws CodecException {
        throw new CodecException("Encoding of packet-in is not supported");
    }

    @Override
    protected PiPacketOperation decode(
            P4RuntimeOuterClass.PacketIn message, Object ignored,
            PiPipeconf pipeconf, P4InfoBrowser browser)
            throws CodecException, P4InfoBrowser.NotFoundException {
        final P4InfoOuterClass.Preamble ctrlPktMetaPreamble = browser
                .controllerPacketMetadatas()
                .getByName(PACKET_IN)
                .getPreamble();
        return PiPacketOperation.builder()
                .withType(PiPacketOperationType.PACKET_IN)
                .withMetadatas(CODECS.packetMetadata().decodeAll(
                        message.getMetadataList(), ctrlPktMetaPreamble, pipeconf))
                .withData(copyFrom(message.getPayload().asReadOnlyByteBuffer()))
                .build();
    }
}
